package com.estun.backroundManagementService.aop.operationLog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.estun.backroundManagementService.aop.operationLog.LogInfo;
import com.estun.backroundManagementService.aop.operationLog.LogInfoQueryRequest;
import com.estun.backroundManagementService.domain.BasePageRequest;
import com.estun.backroundManagementService.domain.BaseResponse;
import com.estun.backroundManagementService.service.LogInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/log")
public class LogController {
    @Autowired
    private LogInfoService logInfoService;

    @GetMapping("/{id}")
    public LogInfo getLogInfoById(@PathVariable Integer id) {
        return logInfoService.getById(id);
    }

    @GetMapping
    public List<LogInfo> getAllLogInfos() {
        return logInfoService.list();
    }

    @PostMapping("/page")
    public BaseResponse pageLogInfo(@RequestBody BasePageRequest<LogInfoQueryRequest> pageRequest) {
        Page<LogInfo> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        QueryWrapper<LogInfo> queryWrapper = new QueryWrapper<>();

        Optional.ofNullable(pageRequest.getQuery()).ifPresent(query -> {
            Optional.ofNullable(query.getModule())
                    .filter(StringUtils::isNotBlank)
                    .ifPresent(moudule -> queryWrapper.like("module", moudule));

            Optional.ofNullable(query.getType())
                    .filter(StringUtils::isNotBlank)
                    .ifPresent(type -> queryWrapper.eq("type", type));

            Optional.ofNullable(query.getUserId())
                    .filter(StringUtils::isNotBlank)
                    .ifPresent(userId -> queryWrapper.eq("user_id", userId));

            if (query.getBeginTime() != null && query.getEndTime() != null) {
                queryWrapper.between("create_time", query.getBeginTime(), query.getEndTime());
            }
        });
        IPage<LogInfo> iPage = logInfoService.page(page, queryWrapper);
        return BaseResponse.success(iPage);
    }
}
